/*
 * sockselect.cpp
 *
 *  Created on: 2012-5-26
 *      Author: epmm
 */

#include "sockselect.h"
int CreateSocket()
{
	int s = 0;
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s < 0)
	{
		return 1;
	}
	return s;
}

int Bind(int listenSock, int port, const char* ip)
{
	sockaddr_in addr;
	addr.sin_family = AF_INET;
	if (ip == NULL)
	{
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
		addr.sin_addr.s_addr = inet_addr(ip);
	}
	addr.sin_port = htons(port);

	if (bind(listenSock, (sockaddr*) &addr, sizeof(sockaddr)))
	{
		return 1;
	}
	return 0;
}

int Listen(int listenSock, int backlog)
{
	int ret = 0;
	ret = listen(listenSock, backlog);
	if (ret < 0)
	{
		return 1;
	}
	return 0;
}

int Initfdset(int listenSock, fd_set* readset, int* fds,size_t size)
{
	FD_ZERO(readset);
	FD_SET(listenSock, readset);

	for (size_t i = 0; i < size; i++)
	{
		FD_SET(fds[i], readset);
	}
	return 0;
}

int Select(int maxfd, fd_set* readfds, fd_set* writefds, fd_set* exceptfds)
{
	int total = 0;
	total = select(maxfd + 1, readfds, writefds, exceptfds, NULL);
	if (total < 0)
	{
		return 1;
	}
	return total;
}

int Accept(int listenfd, fd_set* readset, int* clientfd,
		sockaddr_in* clientaddr)
{
	if (FD_ISSET(listenfd, readset))
	{
 		int len = sizeof(sockaddr_in);
		(*clientfd) = accept(listenfd, (sockaddr*) clientaddr,
				(socklen_t*) &len);

		if ((*clientfd) < 0)
		{
			return -1;
		}
		return (*clientfd);
	}
	return 0;
}
//
//void CreateClientSocketInfo(int fd, sockaddr_in* addr, CLIENTINFOARRAY& ary)
//{
//	CLIENTINFOMATION client;
//
//	memset(&client, 0, sizeof(client));
//
//	client.fd = fd;
//
//	(*client.addr) = (*addr);
//
//	ary.push_back(client);
//}
//
//int FreeClientSocketInfo(int s, CLIENTINFOARRAY& ary)
//{
//	CLIENTINFOARRAY::iterator iter;
//	for (iter = ary.begin(); iter != ary.end(); iter++)
//	{
//		if ((*iter).fd == s)
//		{
//			close((*iter).fd);
//
//			ary.erase(iter);
//
//			return 0;
//		}
//	}
//	return 1;
//}

int Recv(int fds, fd_set* readset, int nFlags ,std::string& strRecvBuf)
{
	int nRecvBytes = 0;
	char sTmpBuf[SOCK_RECVBUFSIZE] = { 0 };

	memset(sTmpBuf, 0, sizeof(sTmpBuf));

	if (FD_ISSET(fds,readset))
	{
 		nRecvBytes = recv(fds, sTmpBuf, SOCK_RECVBUFSIZE, nFlags);
		sTmpBuf[nRecvBytes] = '\0';
		strRecvBuf = sTmpBuf;
		return nRecvBytes;
	}
	return 0;
}


